package com.atguigu.day09;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

public class Flink05_SQL_OverWindow {
    public static void main(String[] args) {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        Configuration configuration = tableEnv.getConfig().getConfiguration();
        configuration.setString("table.local-time-zone", "GMT");


        //TODO 3.创建从文件读数据的表，并指定事件时间
        tableEnv.executeSql("create table sensor(" +
                "id string," +
                "ts bigint," +
                "vc int," +
                "et as to_timestamp(from_unixtime(ts/1000,'yyyy-MM-dd HH:mm:ss'))," +
                "watermark for et as et-interval '5' second" +
                ") with (" +
                "'connector' = 'filesystem'," +
                "'path' = 'input/sensor-sql.txt'," +
                "'format' = 'csv'" +
                ")");

        //TODO 4.开启一个OverWindow
       /* tableEnv.executeSql("select " +
                "id," +
                "ts," +
                "vc," +
                "sum(vc) over(partition by id order by et) " +
                "from sensor" +
                "").print();  */

       //以下写法可以多次使用相同逻辑的OverWindow，不需要每次都写，只需调用即可
        tableEnv.executeSql("select " +
                "id," +
                "ts," +
                "vc," +
                "sum(vc) over w," +
                "count(vc) over w " +
                "from sensor " +
                "window w as (partition by id order by et)" +
                "").print();
    }
}
